

import style from './index.module.scss'
import { getQuestionById } from '@/services/question'
import PageWrapper from '@/components/PageWrapper'
//获取组件信息
import { getQuestionComponent } from '@/components/QuestionComponents'

type propsTyps = {
  error:number,
  data?:{
    id: string,
    title: string,
    desc?: string,
    css?: string,
    js?: string,
    isPublish: boolean,
    isDeleted:boolean,
    componentList: any[]
  }
  msg?:string
}

export default function Home(props: propsTyps) {
  const {error,msg = ''} = props
  if(error !== 0){
    return <PageWrapper title='错误'>
      <h1>错误1</h1>
      <p>{msg}</p>
    </PageWrapper>
  }
  const {id = '',title='',isDeleted,desc,isPublish,componentList} = props.data || {}
  if(isDeleted){
    return <PageWrapper title={title} desc={desc}>
      <h1>{title}</h1>
      <p>该问卷被删除</p>
    </PageWrapper>
  }
  if(!isPublish){
    return <PageWrapper title={title} desc={desc}>
      <h1>{title}</h1>
      <p>该问卷还未发布</p>
    </PageWrapper>
  }

  //循环遍历出组件

  function getComponentsSinal(info:any){
    const showComponent = getQuestionComponent(info)
    if(showComponent == null) return null
    return <div key={info.fe_id} className={style.questionWrapper}>
      {showComponent}
    </div>
  }


  return (
    <PageWrapper title={title} desc={desc}>
      <form method='post' action='/api/answer'>
          {/* 隐藏input 用来保存问卷的id */}
          <input type='hidden' value={id} name = 'questionId' />
          {componentList?.map((item:any)=>{
            return getComponentsSinal(item)
          })}
          <div className={style.submitContainerBtn}>
              <button type='submit'>提交</button>
          </div>
        </form>
    </PageWrapper>
  )
}

export async function getServerSideProps(context: any) {
  const { id } = context.params
  //根据id获取问卷数据
  const data =await getQuestionById(id)
  return {
    props: {
      ...data
    }
  }
}
